import { Upload, Button, Slider, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { useState } from 'react';

const ImageCompressor = () => {
  const [quality, setQuality] = useState(80);
  const [loading, setLoading] = useState(false);

  const handleUpload = async (file: File) => {
    try {
      setLoading(true);
      message.loading('正在压缩图片...', 0);

      const formData = new FormData();
      formData.append('image', file);
      formData.append('quality', quality.toString());

      console.log('Sending request to server...'); // 调试日志
      const response = await fetch('http://localhost:3001/api/compress-image', {
        method: 'POST',
        body: formData,
      });
      
      console.log('Server response:', response.status); // 调试日志
      
      if (response.ok) {
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `compressed_${file.name}`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
        message.destroy();
        message.success('图片压缩成功！');
      } else {
        const errorText = await response.text();
        console.error('Server error:', errorText); // 调试日志
        message.destroy();
        message.error(`图片压缩失败：${errorText}`);
      }
    } catch (error) {
      console.error('Upload error:', error); // 调试日志
      message.destroy();
      message.error('图片压缩失败，请检查网络连接或重试！');
    } finally {
      setLoading(false);
    }
  };

  const beforeUpload = (file: File) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件！');
      return false;
    }
    const isLt20M = file.size / 1024 / 1024 < 20;
    if (!isLt20M) {
      message.error('图片必须小于20MB！');
      return false;
    }
    return true;
  };

  return (
    <div style={{ textAlign: 'center', padding: '20px' }}>
      <h2>图片压缩</h2>
      <div style={{ width: '300px', margin: '20px auto' }}>
        <p>压缩质量: {quality}%</p>
        <Slider
          min={1}
          max={100}
          value={quality}
          onChange={setQuality}
          disabled={loading}
        />
      </div>
      <Upload
        customRequest={({ file }) => handleUpload(file as File)}
        showUploadList={false}
        accept="image/*"
        beforeUpload={beforeUpload}
        disabled={loading}
      >
        <Button icon={<UploadOutlined />} loading={loading}>
          {loading ? '压缩中...' : '选择图片'}
        </Button>
      </Upload>
      <p style={{ marginTop: '20px' }}>支持JPG、PNG等格式，文件大小限制为20MB</p>
    </div>
  );
};

export default ImageCompressor; 